package org.grayrabbit.cloud.core.mina;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.grayrabbit.cloud.core.biz.BizResult;
import org.grayrabbit.cloud.core.rpc.Argument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class ResultHandler extends IoHandlerAdapter {
	private final static Logger logger = LoggerFactory.getLogger(ResultHandler.class);
	private Argument argument;
	private BizResult result;
	public ResultHandler(Argument argument){
		this.argument = argument;
	}


	@Override
	public void sessionOpened(IoSession session) throws Exception {
		session.write(argument);
		logger.debug("Session opened,写数据完成!");
	}

	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {
		if(message instanceof BizResult){
			result= (BizResult) message;
			logger.debug("接收到处理结果:{}",result.getResult());
			//handler.handle(argument, channel);
			session.close(true);
		}else{
			logger.debug("Server error, disconnecting...");
			session.close(true);
		}
	}

	public BizResult getResult() {
		return result;
	}


	@Override
	public void exceptionCaught(IoSession session, Throwable cause)
			throws Exception {
		logger.error("通信异常",cause);
		session.close(true);
		result = BizResult.create(cause);
	}
	
}
